const ExcelJs = require('exceljs');
require('chromedriver');
const webDriver = require('selenium-webdriver'),
    By = webDriver.By;
const driver = new webDriver.Builder()
    .forBrowser('chrome')
    .build();
const { waitTime } = require('../common');
const request = require('request-promise');

async function Request(cookies, reference) {
    const options = {
        uri: 'https://portal.cinfrance.fr/api/stockAccounts?awb=reference&awb=quantity&awb=weight&awb=description&awb=mrn&awb=flight&awb=date&awb=routing&awb=chargeDeclaration&awb=status&awb=agent&awb=shipper&awb=consignee&flight=reference&flight=routing&flight=status&flight=quantity&flight=uld&flight=weight&flight=volume&flight=description&reference=' + reference,
        method: 'GET',
        headers: {
            Cookie: cookies
        },
        json: true
    };
    try {
        console.info(`请求获取 ${reference}`);
        setTimeout(() => {
            console.log('time out');
            clearTimeout();
            return [];
        }, 5000);
        return await request(options);
    } catch (e) {
        const error = `Request Error: ${JSON.stringify(e.message || e)}`;
        console.error(error);
    }
}

async function load() {
    await login();
    console.log('已登录');
    const workbook = new ExcelJs.Workbook();
    await workbook.xlsx.readFile('../file/in/batch.xlsx');
    const worksheet1 = workbook.getWorksheet(1);
    let batch = '';
    const result = [];
    let index = 2;
    while (index > 1) {
        batch = worksheet1.getRow(index).getCell(1).value;
        if (!batch || batch.length === 0) {
            index = -1;
            return;
        }
        await driver.get(`https://portal.cinfrance.fr/#/stockAccounts/list?awb=reference&awb=quantity&awb=weight&awb=description&awb=mrn&awb=flight&awb=date&awb=routing&awb=chargeDeclaration&awb=status&awb=agent&awb=shipper&awb=consignee&flight=reference&flight=routing&flight=status&flight=quantity&flight=uld&flight=weight&flight=volume&flight=description`);
        await waitTime(2000);
        await driver.findElement(By.xpath('/html/body/ui-view/div/div[2]/ui-view/div/div/div[1]/cin-panel/div/div[2]/div/form/div[1]/div[2]/div[1]/input')).sendKeys(batch);
        await waitTime(1000);
        await driver.findElement(By.xpath('/html/body/ui-view/div/div[2]/ui-view/div/div/div[1]/cin-panel/div/div[2]/div/form/div[2]/button[1]')).click();
        await waitTime(2000);
        const trs = await driver.findElement(By.xpath('/html/body/ui-view/div/div[2]/ui-view/div/div/div[1]/div[2]/div/div/div/table/tbody')).findElements(By.tagName('tr'));
        if (trs.length > 0) {
            const tds = await trs[0].findElements(By.tagName('td'));
            console.log(trs[0].getAttributeNames());
            console.info(`第 ${index - 1}个处理结束，${batch} 处理结束`);
        }
        console.info(`第 ${index - 1}个处理结束，${batch} 处理结束`);
        await waitTime(500);
        index++;
    }
    return result;
}

async function loadFile() {
    const cookies = await login();
    await driver.quit();
    console.info('已获取cookies');
    const workbook = new ExcelJs.Workbook();
    await workbook.xlsx.readFile('../file/in/batch.xlsx');
    const worksheet1 = workbook.getWorksheet(1);
    let batch = '';
    const result = [];
    let index = 2;
    while (index > 1) {
        batch = worksheet1.getRow(index).getCell(1).value;
        if (!batch || batch.length === 0) {
            index = -1;
            return;
        }
        const response = await Request(cookies ,batch);
        if (response.length > 0) {
            const col0 = response[0].columns;
            const awb = {};
            awb.agent = col0['awb.agent'];
            awb.consignee = col0['awb.consignee'];
            awb.shipper = col0['awb.shipper'];
            awb.chargeDeclaration = col0['awb.chargeDeclaration'];
            awb.mrn = col0['awb.mrn'];
            awb.routing = col0['awb.routing'];
            awb.flight = col0['awb.flight'];
            awb.status = col0['awb.status'];
            awb.date = col0['awb.date'];
            awb.reference = col0['awb.reference'];
            awb.weight = col0['awb.weight'];
            awb.quantity = col0['awb.quantity'];
            awb.description = col0['awb.description'];
            const flights = [];
            for (const res of response) {
                flights.push({
                    description: (res.columns)['flight.description'],
                    routing: (res.columns)['flight.routing'],
                    volume: (res.columns)['flight.volume'],
                    quantity: (res.columns)['flight.quantity'],
                    status: (res.columns)['flight.status'],
                    weight: (res.columns)['flight.weight'],
                    reference: (res.columns)['flight.reference'],
                    uld: (res.columns)['flight.uld'],
                })
            }
            awb.flight = flights;
            result.push(awb);
        }
        console.info(`第 ${index - 1}个处理结束，${batch} 处理结束`);
        await waitTime(500);
        index++;
    }
    return result;
}

async function writeExcel(data) {
    const workbook = new ExcelJs.Workbook();
    const sheet = workbook.addWorksheet('My Sheet');
    for (const awb of data) {
        const flights = awb.flight;
        delete awb.flight;
        sheet.addRow(awb);
        for (const flight of flights) {
            sheet.addRow(flight);
        }
    }
    await workbook.xlsx.writeFile('../file/in/batch_result.xlsx');
}

async function login() {
    const loginAs = 'bertrand.waltz@ftl-express.fr';
    const name = 'bertrand.waltz@ftl-express.fr';
    const passwordHash = 'b5106fa3a81451787e77808f8328d51e';
    const password = 'myF744YBd';

    await driver.get('https://portal.cinfrance.fr/#/login');
    await waitTime(5000);
    await driver.findElement(By.name('login')).sendKeys(loginAs);
    await driver.findElement(By.name('password')).sendKeys(password);
    await driver.findElement(By.className('expand ng-binding')).click();
    await waitTime(4000);
    const cookies = await driver.manage().getCookies();
    const result = cookies.map(item => {
        return `${item.name.toString()}=${item.value.toString()}`;
    }, []);
    return result.join(';');
}

async function play() {
    const result = await loadFile();
    console.info('信息获取结束！')
    await writeExcel(result);
    console.info('文件处理结束')
}

play().then(err => {
    if (err) {
        console.error(err);
    } else {
        console.info('success');
    }
})
